package org.inter.fsb.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.inter.fsb.entity.*;
import org.inter.fsb.mapper.UserMapper;
import org.inter.fsb.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.inter.fsb.utils.DESUtil;
import org.inter.fsb.utils.JwtTokenUtil;
import org.inter.fsb.utils.MapEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author syg
 * @since 2022-11-25
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    public static Map<String,String> smsMap = new HashMap<>();

    @Override
    public Map login(User user) throws Exception {
        Map result = new HashMap();
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User dbUser = this.getOne(userQueryWrapper);

        if (user.getUsername() == null || "".equals(user.getUsername())) {
            throw new Exception("用户名不可为空");
        }

        //验证码判断
//        String smsCode = smsMap.get(user.getUsername());
//        if (smsCode != null){
//            if (!smsCode.equals(user.getPassword())){
//                throw new Exception("验证码错误");
//            }
//        }else {
//            throw new Exception("验证码错误");
//        }


        if (dbUser == null) {
            user.setJine(new BigDecimal(0));
            user.setDeptId(0);
            this.saveOrUpdate(user);
            result.put("token", jwtTokenUtil.generateToken(user.getUsername(), "randoms"));

            return result;


        } else {

            result.put("token", jwtTokenUtil.generateToken(dbUser.getUsername(), "randoms"));

            return result;

        }


    }

    @Override
    public void iDcardRe(String username,String name,String number) throws Exception {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User one = this.getOne(userQueryWrapper);
        if (one == null){
            throw new Exception("系统错误");
        }

        String host = "https://api12.aliyun.venuscn.com";
        String path = "/cert/id-card";
        String appcode = "256eaa0e4a594b64b9e44eff3b28620f";
//        Map<String, Object> headers = new HashMap<String, Object>();
        //最后在 header 中的格式(中间是英文空格)为Authorization:APPCODE83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, Object> querys = new HashMap<String, Object>();
        querys.put("name", name);
        querys.put("number", number);


            /**
             16. * 重要提示如下:
             17. * HttpUtils 请从
             18. * https://github.com/aliyun/api-gateway-demo-signjava/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.ja
             va
             19. * 下载
             20. *
             21. * 相应的依赖请参照
             22. * https://github.com/aliyun/api-gateway-demo-signjava/blob/master/pom.xml
             23. */

            String request = HttpRequest.get(host + path)
                    .header("Authorization","APPCODE" + " "  + appcode)
                    .form(querys)
                    .timeout(20000)
                    .execute().body()

                    ;
            Map resMap =  JSONObject.parseObject(request);
            System.out.println(resMap.get("ret"));
            //获取 response 的 body
            if (!"200".equals(resMap.get("ret").toString())){
                throw new Exception("身份认证失败");
            }
            one.setDeptId(1);
            one.setName(name);
            one.setAddress(number);
            this.saveOrUpdate(one);

            //System.out.println(EntityUtils.toString(response.getEntity()));


    }


    @Override
    public void sms(String phoneNumber) {
        int APP_ID = 1400847456;  // 替换成自己的AppID
        String APP_KEY = "181338708cf41af45594b8c6099fba90";  // 替换成自己的AppKey
        int TEMPLATE_ID = 1907795;  // 替换成自己的短信模板ID
        String signContent = "新米数据服务有限公司";
        try {
            // 实例化一个SmsSingleSender对象
            SmsSingleSender sender = new SmsSingleSender(APP_ID, APP_KEY);
            String verificationCode = Integer.toString(100000 + new Random().nextInt(900000));;  // 替换成生成的验证码
            String time = "10";
            // 指定短信模板参数，将验证码替换到模板的参数中
            String[] params = {verificationCode,time};

            smsMap.put(phoneNumber,verificationCode);

            // 发送短信验证码
            SmsSingleSenderResult result = sender.sendWithParam("86", phoneNumber, TEMPLATE_ID, params, signContent, "", "");

            // 解析短信发送结果
            if (result.result == 0) {
                System.out.println("短信发送成功！");
            } else {
                System.out.println("短信发送失败：" + result.errMsg);
            }
        } catch (HTTPException e) {
            System.err.println("HTTP响应码错误：" + e.getStatusCode()+ "，错误信息：" + e.getMessage());
        } catch (IOException e) {
            System.err.println("网络IO错误：" + e.getMessage());
        }
    }

    @Override
    public void chongzhi(String username, BigDecimal money) throws Exception {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = this.getOne(userQueryWrapper);
        if (money == null || user == null){
            throw new Exception("系统错误");
        }
        user.setJine(user.getJine().add(money));
        this.saveOrUpdate(user);
    }


}














